package com.peng.herostory;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import com.peng.herostory.msg.GameMsgProtocol;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public final class GameMsgRecognizer {
    private static Map<Class<?>, Integer> msgClazzAndCodeMap = new HashMap<>();
    private static Map<Integer, GeneratedMessageV3> msgCodeAndMsgEntityMap = new HashMap<>();

    public static void init() {
        Class<?>[] declaredClasses = GameMsgProtocol.class.getDeclaredClasses();
        for (Class<?> declaredClass : declaredClasses) {
            if (!GeneratedMessageV3.class.isAssignableFrom(declaredClass)) {
                continue;
            }
            String className = declaredClass.getSimpleName().toLowerCase();
            log.info("msgClassName:{}", className);
            for (GameMsgProtocol.MsgCode msgCodeValue : GameMsgProtocol.MsgCode.values()) {
                String msgName = msgCodeValue.name().replaceAll("_", "").toLowerCase();
                if (!className.equals(msgName)) {
                    continue;
                }
                try {
                    Object getDefaultInstance = declaredClass.getDeclaredMethod("getDefaultInstance").invoke(declaredClass);
                    log.info("{} <==> {}", declaredClass.getName(), msgCodeValue.getNumber());
                    msgCodeAndMsgEntityMap.put(msgCodeValue.getNumber(), (GeneratedMessageV3) getDefaultInstance);
                    msgClazzAndCodeMap.put(getDefaultInstance.getClass(), msgCodeValue.getNumber());

                } catch (Exception e) {
                    log.error("e:{}", e);
                }

            }

        }
//        msgClazzAndCodeMap.put(GameMsgProtocol.UserEntryResult.class,GameMsgProtocol.MsgCode.USER_ENTRY_RESULT_VALUE);
//        msgClazzAndCodeMap.put(GameMsgProtocol.WhoElseIsHereResult.class,GameMsgProtocol.MsgCode.WHO_ELSE_IS_HERE_RESULT_VALUE);
//        msgClazzAndCodeMap.put(GameMsgProtocol.UserMoveToResult.class,GameMsgProtocol.MsgCode.USER_MOVE_TO_RESULT_VALUE);
//        msgClazzAndCodeMap.put(GameMsgProtocol.UserQuitResult.class,GameMsgProtocol.MsgCode.USER_QUIT_RESULT_VALUE);
//
//        msgCodeAndMsgEntityMap.put(GameMsgProtocol.MsgCode.USER_ENTRY_CMD_VALUE,GameMsgProtocol.UserEntryCmd.getDefaultInstance());

    }


    public static Integer getCodeByMsgClazz(Class<?> msgClazz) {
        if (msgClazz == null) {
            return null;
        }
        return msgClazzAndCodeMap.get(msgClazz);
    }

    public static Message.Builder getMsgBuilderByCode(int msgCode) {

        GeneratedMessageV3 generatedMessageV3 = msgCodeAndMsgEntityMap.get(msgCode);
        if (generatedMessageV3 == null) {
            return null;
        }
        return generatedMessageV3.newBuilderForType();

    }

}
